<template>
    <div class="attribute-info">
        <div class="component-title">
            <h3>商品属性信息</h3>
        </div>

        <el-form :model="form" label-width="120px" ref="attributeForm">
            <!-- 加载中提示 -->
            <div v-if="isLoading" class="loading-container">
                <i class="el-icon-loading"></i>
                <p>属性加载中...</p>
            </div>

            <!-- 无属性时的提示 -->
            <div class="empty-tip" v-else-if="!attributeOptions || attributeOptions.length === 0">
                <i class="el-icon-warning-outline"></i>
                <p>请先选择商品分类，系统将自动加载对应的属性</p>
            </div>

            <!-- 销售属性部分 -->
            <div class="form-section" v-if="salesAttributes.length > 0">
                <div class="section-title">
                    <i class="el-icon-s-operation"></i>
                    <span>销售属性</span>
                </div>

                <p class="section-desc">销售属性将用于生成SKU，请谨慎选择</p>

                <el-form-item v-for="attr in salesAttributes" :key="attr.id" :label="attr.name"
                    :prop="attr.id.toString()">
                    <el-select v-if="attr.input_type === 'select'" v-model="form[attr.id]" placeholder="请选择">
                        <el-option v-for="option in attr.options" :key="option.value" :label="option.label"
                            :value="option.value"></el-option>
                    </el-select>

                    <el-input v-else-if="attr.input_type === 'text'" v-model="form[attr.id]"
                        placeholder="请输入"></el-input>

                    <el-checkbox-group v-else-if="attr.input_type === 'checkbox'" v-model="form[attr.id]">
                        <el-checkbox v-for="option in attr.options" :key="option.value" :label="option.value">{{
                            option.label }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </div>

            <!-- 参数属性部分 -->
            <div class="form-section" v-if="paramAttributes.length > 0">
                <div class="section-title">
                    <i class="el-icon-s-grid"></i>
                    <span>参数属性</span>
                </div>

                <p class="section-desc">参数属性用于展示商品的特性和规格</p>

                <el-form-item v-for="attr in paramAttributes" :key="attr.id" :label="attr.name"
                    :prop="attr.id.toString()">
                    <el-select v-if="attr.input_type === 'select'" v-model="form[attr.id]" placeholder="请选择">
                        <el-option v-for="option in attr.options" :key="option.value" :label="option.label"
                            :value="option.value"></el-option>
                    </el-select>

                    <el-input v-else-if="attr.input_type === 'text'" v-model="form[attr.id]"
                        placeholder="请输入"></el-input>

                    <el-checkbox-group v-else-if="attr.input_type === 'checkbox'" v-model="form[attr.id]">
                        <el-checkbox v-for="option in attr.options" :key="option.value" :label="option.value">{{
                            option.label }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </div>

            <!-- 物流信息部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-truck"></i>
                    <span>物流信息</span>
                </div>

                <p class="section-desc">物流信息将用于计算运费</p>

                <div class="form-row">
                    <el-form-item label="重量 (kg)" prop="weight">
                        <el-input-number v-model="form.weight" :precision="2" :step="0.1" :min="0"
                            controls-position="right"></el-input-number>
                    </el-form-item>

                    <el-form-item label="体积 (m³)" prop="volume">
                        <el-input-number v-model="form.volume" :precision="3" :step="0.001" :min="0"
                            controls-position="right"></el-input-number>
                    </el-form-item>
                </div>
            </div>

            <!-- 自定义属性部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-plus"></i>
                    <span>自定义属性</span>
                </div>

                <p class="section-desc">您可以添加系统中没有的自定义属性</p>

                <div v-for="(item, index) in customAttributes" :key="index" class="custom-attribute-item">
                    <el-input v-model="item.name" placeholder="属性名称" class="attribute-name"></el-input>
                    <el-input v-model="item.value" placeholder="属性值" class="attribute-value"></el-input>
                    <el-button type="danger" icon="el-icon-delete" circle @click="removeCustomAttribute(index)"
                        size="mini"></el-button>
                </div>

                <div class="add-attribute">
                    <el-button type="primary" size="small" @click="addCustomAttribute">
                        <i class="el-icon-plus"></i> 添加自定义属性
                    </el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    name: 'AttributeInfo',
    props: {
        formData: {
            type: Object,
            required: true
        },
        attributeOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            form: {
                ...this.formData,
                weight: this.formData.weight || 0,
                volume: this.formData.volume || 0
            },
            customAttributes: [],
            isLoading: false,
            attributeCache: new Map() // 缓存属性值，避免重复计算
        };
    },
    computed: {
        salesAttributes() {
            // 使用缓存提高性能
            if (this.attributeCache.has('sales')) {
                return this.attributeCache.get('sales');
            }

            const result = this.attributeOptions.filter(attr => attr.type === 2);
            this.attributeCache.set('sales', result);
            return result;
        },
        paramAttributes() {
            // 使用缓存提高性能
            if (this.attributeCache.has('param')) {
                return this.attributeCache.get('param');
            }

            const result = this.attributeOptions.filter(attr => attr.type === 3);
            this.attributeCache.set('param', result);
            return result;
        }
    },
    watch: {
        formData: {
            handler(val) {
                // 避免不必要的深拷贝，只在真正需要更新时才更新
                const needUpdate = JSON.stringify(this.form) !== JSON.stringify(val);
                if (needUpdate) {
                    this.form = {
                        ...val,
                        weight: val.weight || 0,
                        volume: val.volume || 0
                    };
                }
            },
            deep: true
        },
        form: {
            handler(val) {
                try {
                    // 使用防抖减少频繁更新
                    this.debouncedEmitUpdate(val);
                } catch (error) {
                    console.error('更新属性表单失败:', error);
                }
            },
            deep: true
        },
        attributeOptions: {
            handler(val) {
                // 清除缓存
                this.attributeCache.clear();

                // 初始化表单数据
                if (val && val.length > 0) {
                    try {
                        this.isLoading = true;

                        // 分批处理属性，避免一次性处理过多导致卡顿
                        this.processAttributesBatched(val);
                    } catch (error) {
                        console.error('初始化属性失败:', error);
                        this.isLoading = false;
                    }
                }
            },
            immediate: true
        }
    },
    created() {
        // 创建防抖函数
        this.debouncedEmitUpdate = this.debounce(this.emitUpdate, 300);
    },
    methods: {
        debounce(fn, delay) {
            let timer = null;
            return function (...args) {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(this, args);
                }, delay);
            };
        },
        emitUpdate(val) {
            const formData = { ...val };

            // 添加自定义属性到表单数据
            if (this.customAttributes.length > 0) {
                formData.custom_attributes = this.customAttributes.filter(
                    item => item.name && item.value
                );
            }

            this.$emit('update-form', formData);
        },
        processAttributesBatched(attributes) {
            const batchSize = 10;
            const totalAttributes = attributes.length;
            let processedCount = 0;

            const processBatch = (startIndex) => {
                const endIndex = Math.min(startIndex + batchSize, totalAttributes);
                const batch = attributes.slice(startIndex, endIndex);

                batch.forEach(attr => {
                    if (!this.form[attr.id]) {
                        if (attr.input_type === 'checkbox') {
                            this.$set(this.form, attr.id, []);
                        } else {
                            this.$set(this.form, attr.id, '');
                        }
                    }
                });

                processedCount += batch.length;

                if (processedCount < totalAttributes) {
                    // 使用requestAnimationFrame优化性能
                    window.requestAnimationFrame(() => {
                        processBatch(endIndex);
                    });
                } else {
                    this.isLoading = false;
                }
            };

            // 开始处理第一批
            processBatch(0);
        },
        addCustomAttribute() {
            if (this.customAttributes.length >= 20) {
                this.$message.warning('自定义属性最多添加20个');
                return;
            }

            this.customAttributes.push({
                name: '',
                value: ''
            });
        },
        removeCustomAttribute(index) {
            if (index >= 0 && index < this.customAttributes.length) {
                this.customAttributes.splice(index, 1);
            }
        },
        validate() {
            return new Promise((resolve, reject) => {
                try {
                    this.$refs.attributeForm.validate(valid => {
                        if (valid) {
                            // 验证自定义属性
                            const invalidCustom = this.customAttributes.find(
                                attr => (attr.name && !attr.value) || (!attr.name && attr.value)
                            );

                            if (invalidCustom) {
                                reject(new Error('自定义属性的名称和值必须同时填写或同时为空'));
                                return;
                            }

                            resolve(true);
                        } else {
                            reject(new Error('属性信息验证失败'));
                        }
                    });
                } catch (error) {
                    reject(error || new Error('属性信息验证失败'));
                }
            });
        }
    }
};
</script>

<style scoped>
.attribute-info {
    padding: 20px;
}

.component-title {
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.component-title h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.form-section {
    margin-bottom: 30px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.section-title i {
    margin-right: 8px;
    color: #409EFF;
}

.section-desc {
    color: #999;
    font-size: 12px;
    margin-bottom: 20px;
}

.form-row {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.form-row .el-form-item {
    flex: 1;
    min-width: 200px;
}

.empty-tip {
    text-align: center;
    padding: 40px 0;
    color: #999;
}

.empty-tip i {
    font-size: 48px;
    color: #ddd;
    margin-bottom: 15px;
}

.custom-attribute-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    gap: 10px;
}

.attribute-name {
    width: 200px;
}

.attribute-value {
    flex: 1;
}

.add-attribute {
    margin-top: 15px;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
}

.loading-container i {
    font-size: 32px;
    color: #409EFF;
    margin-bottom: 15px;
}
</style>